package com.elite.groovy.callback

import com.elite.groovy.davco.clink.ClinkUtils
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * @projectName: Groovy
 * @package: com.elite.groovy.callback
 * @className: apiClinkCdrComments
 * @description: 同步天润留言&满意度记录数据
 * @author: LiJT
 * @date: 2023-10-27 11:13
 * @version: 1.0
 */

public class apiClinkCdrComments implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiClinkCdrComments.class);

    private static boolean isRun = true;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        try {

            String StartTime = request.getParameter("StartTime");
            String EndTime = request.getParameter("EndTime");
            log.debug("doCallBack API StartTime:" + StartTime + " EndTime:" + EndTime);

            long currentTimeMillis = (long) (System.currentTimeMillis() / 1000);
            String StartTimeDefault = String.valueOf((currentTimeMillis - 172800));
            String EndTimeDefault = String.valueOf(currentTimeMillis);

            StartTime = KHUtil.isNull(StartTime) ? StartTimeDefault : StartTime;
            EndTime = KHUtil.isNull(EndTime) ? EndTimeDefault : EndTime;
            log.debug("同步天润留言&满意度记录数据 StartTime:" + StartTime + "(" + stampToDate(StartTime) + ")" + " EndTime:" + EndTime + "(" + stampToDate(EndTime) + ")");

            // 获取数据源
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 同步留言记录数据
            int Offset = 0;
            isRun = true;
            log.debug("同步留言记录数据...");

            while (isRun && Offset < 1000) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("同步留言记录数据...偏移Offset:" + Offset);
                toDoCommentsGet(jt, Long.parseLong(StartTime), Long.parseLong(EndTime), Offset * 100);
                Offset = Offset + 1;
            }

            // 同步满意度记录数据
            Offset = 0;
            isRun = true;
            log.debug("同步满意度记录数据...");
            while (isRun && Offset < 1000) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("同步满意度记录数据...偏移Offset:" + Offset);
                toDoOBGet(jt, Long.parseLong(StartTime), Long.parseLong(EndTime), Offset * 100);
                Offset = Offset + 1;
            }

            log.debug("数据同步任务结束执行...");
        } catch (Exception e) {
            log.error("HTTP请求调用错误，接口处理异常：" + e.getMessage());
            return e.getMessage();

        }

        return "SUCC";

    }

    // 1-同步留言记录数据
    static toDoCommentsGet(JdbcTemplate jt, Long StartTime, Long EndTime, int Offset) {

        //处理主数据
        log.debug("1-同步留言记录数据 toDoGet Data StartTime:" + StartTime + " EndTime:" + EndTime + " Offset:" + Offset);

        // 封装调用头Heads
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");

        // 系统接入-GET
        String getPath = "/cc/list_comments?";

        Map<String, String> queryParams = new HashMap<String, String>();
        queryParams.put("startTime", String.valueOf(StartTime));
        queryParams.put("endTime", String.valueOf(EndTime));
        queryParams.put("offset", String.valueOf(Offset));
        queryParams.put("limit", "100");
        String doGETRes = ClinkUtils.doClinkCall("GET", getPath, queryParams, headMap, null);
        // log.debug("系统接入 doGETRes:" + doGETRes);

        JSONObject doGETJSON = JSONObject.fromObject(doGETRes);
        // log.debug("1-同步留言记录数据 Data Result:" + doGETJSON);

        JSONArray dataArray = doGETJSON.getJSONArray("cdrComments"); ;
        int dataArrayLen = dataArray.size();

        log.debug("1-同步留言记录数据 Data Result size:" + dataArrayLen);
        if (dataArrayLen <= 0) {
            isRun = false;
        }

        JSONObject dataObject = null;
        String sql = null;
        List sqlResult = null;
        int Countnum = 0;
        for (int i = 0; i < dataArrayLen; i++) {
            dataObject = dataArray.getJSONObject(i);
            String uniqueId = KHUtil.GetSFJV(dataObject, "uniqueId");
            String customerNumber = KHUtil.GetSFJV(dataObject, "customerNumber");
            String customerArea = KHUtil.GetSFJV(dataObject, "customerArea");
            String hotline = KHUtil.GetSFJV(dataObject, "hotline");
            String startTime = KHUtil.GetSFJV(dataObject, "startTime");
            String endTime = KHUtil.GetSFJV(dataObject, "endTime");
            String bridgeDuration = KHUtil.GetSFJV(dataObject, "bridgeDuration");
            String voiceMail = KHUtil.GetSFJV(dataObject, "voiceMail");
            String recordFile = KHUtil.GetSFJV(dataObject, "recordFile");
            // log.debug("1-同步留言记录数据 Deal Data uniqueId:" + uniqueId);

            // 检查当前数据库是否存在 存在更新 不存在新建
            sql = "Select Count(*) As Count From clink_list_comments Where uniqueId = ?";
            sqlResult = jt.queryForList(sql, uniqueId);
            Countnum = sqlResult.get(0).get("Count") as int;
            // log.debug("1-同步留言记录数据 检查当前数据库是否存在:" + Countnum);

            if (Countnum <= 0) {

                sql = '''Insert Into Clink_List_Comments
                          (Uniqueid, Customernumber, Customerarea, Hotline, Starttime, Endtime, Bridgeduration, Voicemail, Recordfile)
                        Values
                          (?, ?, ?, ?, ?, ?, ?, ?, ?)''';

                jt.update(sql, uniqueId, customerNumber, customerArea, hotline, startTime, endTime, bridgeDuration, voiceMail, recordFile);

                sql = '''Replace Into Voicemail
                      (Voicemail_Guid, Dnis, Ani, Starttime, Endtime, Documentpath)
                      Select Uniqueid As Voicemail_Guid,
                             Hotline As Dnis,
                             Customernumber As Ani,
                             If(Starttime Is Not Null And Starttime != '', Date_Format(From_Unixtime(Starttime), '%Y-%m-%d %H:%i:%s'), Null) As Starttime,
                             If(Endtime Is Not Null And Endtime != '', Date_Format(From_Unixtime(Endtime), '%Y-%m-%d %H:%i:%s'), Null) As Endtime,
                             Replace(R2.Parametervalue, '[UCID]', Uniqueid) As Documentpath
                        From Clink_List_Comments R1
                        Left Join Sysc_Parameter R2
                          On R2.Parameter_Id = 'RECURL'
                         And (R2.Rolegroup_Id Is Null Or R2.Rolegroup_Id = '')
                        Where R1.Uniqueid = ?''';
                jt.update(sql, uniqueId);

            } else {
                sql = '''Update Clink_List_Comments
                           Set Customernumber = ?,
                               Customerarea   = ?,
                               Hotline        = ?,
                               Starttime      = ?,
                               Endtime        = ?,
                               Bridgeduration = ?,
                               Voicemail      = ?,
                               Recordfile     = ?
                         Where Uniqueid = ?''';

                jt.update(sql, customerNumber, customerArea, hotline, startTime, endTime, bridgeDuration, voiceMail, recordFile, uniqueId);
            }
        }

    }

    // 2-同步满意度记录数据
    static toDoOBGet(JdbcTemplate jt, Long StartTime, Long EndTime, int Offset) {

        //处理主数据
        log.debug("2-同步满意度记录数据 toDoGet Data StartTime:" + StartTime + " EndTime:" + EndTime + " Offset:" + Offset);

        // 封装调用头Heads
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");

        // 系统接入-GET
        String getPath = "/cc/list_investigations?";

        Map<String, String> queryParams = new HashMap<String, String>();
        queryParams.put("startTime", String.valueOf(StartTime));
        queryParams.put("endTime", String.valueOf(EndTime));
        queryParams.put("offset", String.valueOf(Offset));
        queryParams.put("limit", "100");
        String doGETRes = ClinkUtils.doClinkCall("GET", getPath, queryParams, headMap, null);
        // log.debug("系统接入 doGETRes:" + doGETRes);

        JSONObject doGETJSON = JSONObject.fromObject(doGETRes);
        // log.debug("2-同步满意度记录数据 Data Result:" + doGETJSON);

        JSONArray dataArray = doGETJSON.getJSONArray("cdrInvestigations"); ;
        int dataArrayLen = dataArray.size();

        log.debug("2-同步满意度记录数据 Data Result size:" + dataArrayLen);
        if (dataArrayLen <= 0) {
            isRun = false;
        };

        JSONObject dataObject = null;
        String sql = null;
        List sqlResult = null;
        int Countnum = 0;
        for (int i = 0; i < dataArrayLen; i++) {
            dataObject = dataArray.getJSONObject(i);
            String mainUniqueId = KHUtil.GetSFJV(dataObject, "mainUniqueId");
            String hotline = KHUtil.GetSFJV(dataObject, "hotline");
            String numberTrunk = KHUtil.GetSFJV(dataObject, "numberTrunk");
            String queue = KHUtil.GetSFJV(dataObject, "queue");
            String customerNumber = KHUtil.GetSFJV(dataObject, "customerNumber");
            String callType = KHUtil.GetSFJV(dataObject, "callType");
            String cno = KHUtil.GetSFJV(dataObject, "cno");
            String clientName = KHUtil.GetSFJV(dataObject, "clientName");
            String transfer = KHUtil.GetSFJV(dataObject, "transfer");
            String consult = KHUtil.GetSFJV(dataObject, "consult");
            String startTime = KHUtil.GetSFJV(dataObject, "startTime");
            String endTime = KHUtil.GetSFJV(dataObject, "endTime");
            String keys = KHUtil.GetSFJV(dataObject, "keys");
            String recordFile = KHUtil.GetSFJV(dataObject, "recordFile");
            String customerCity = KHUtil.GetSFJV(dataObject, "customerCity");
            String customerProvince = KHUtil.GetSFJV(dataObject, "customerProvince");
            String bridgeDuration = KHUtil.GetSFJV(dataObject, "bridgeDuration");
            // log.debug("2-同步满意度记录数据 Deal Data mainUniqueId:" + mainUniqueId);

            // 检查当前数据库是否存在 存在更新 不存在新建
            sql = "Select Count(*) As Count From Clink_List_Investigations Where Mainuniqueid = ?";
            sqlResult = jt.queryForList(sql, mainUniqueId);
            Countnum = sqlResult.get(0).get("Count") as int;
            // log.debug("2-同步满意度记录数据 检查当前数据库是否存在:" + Countnum);

            if (Countnum <= 0) {

                sql = '''Insert Into Clink_List_Investigations
                          (Mainuniqueid,
                           Hotline,
                           Numbertrunk,
                           Queue,
                           Customernumber,
                           Calltype,
                           Cno,
                           Clientname,
                           Transfer,
                           Consult,
                           Starttime,
                           Endtime,
                           `Keys`,
                           Recordfile,
                           Customercity,
                           Customerprovince,
                           Bridgeduration)
                        Values
                          (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''';

                jt.update(sql, mainUniqueId, hotline, numberTrunk, queue, customerNumber, callType, cno, clientName, transfer, consult, startTime, endTime, keys, recordFile, customerCity, customerProvince, bridgeDuration);

            } else {
                sql = '''Update Clink_List_Investigations
                           Set Hotline          = ?,
                               Numbertrunk      = ?,
                               Queue            = ?,
                               Customernumber   = ?,
                               Calltype         = ?,
                               Cno              = ?,
                               Clientname       = ?,
                               Transfer         = ?,
                               Consult          = ?,
                               Starttime        = ?,
                               Endtime          = ?,
                               `Keys`          = ?,
                               Recordfile       = ?,
                               Customercity     = ?,
                               Customerprovince = ?,
                               Bridgeduration   = ?
                         Where Mainuniqueid = ?''';

                jt.update(sql, hotline, numberTrunk, queue, customerNumber, callType, cno, clientName, transfer, consult, startTime, endTime, keys, recordFile, customerCity, customerProvince, bridgeDuration, mainUniqueId);
            }
        }

    }

    static String stampToDate(String s) {
        String res = s.length() > 10 ? s : s + "000";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        long lt = new Long(res);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

}